package com.njit.farm.service.impl;

import com.njit.farm.dao.FUserMapper;
import com.njit.farm.dataobject.FUser;
import com.njit.farm.model.Result;
import com.njit.farm.service.UserService;
import com.njit.farm.util.CheckUtils;
import com.njit.farm.util.IDUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    FUserMapper userMapper;

    @Override
    public Result register(String phone, String pwd) {

        Result result = new Result();


        if (!CheckUtils.checkPhone(phone)) {
            result.setSucc(false);
            result.setMsg("请输入正确的手机号");
            return result;
        }

        FUser regUser = userMapper.selectByPhone(phone);
        if (regUser != null) {
            result.setSucc(false);
            result.setMsg("该手机号已被注册");
            return result;
        }

        if (!CheckUtils.checkPwd(pwd)) {
            result.setSucc(false);
            result.setMsg("密码必须由数字、字母或特殊字符(#@.)组成，长度为8-16位");
            return result;
        }

        FUser fUser = new FUser();
        fUser.setId(IDUtils.uuid());
        fUser.setIntegral(0);
        fUser.setMoney(0f);
        fUser.setPhone(phone);
        fUser.setPwd(DigestUtils.md5Hex(pwd).toUpperCase());

        userMapper.insert(fUser);

        result.setSucc(true);
        return result;
    }

    @Override
    public Result login(String phone, String pwd) {

        Result result = new Result();

        if (!CheckUtils.checkPhone(phone)) {
            result.setSucc(false);
            result.setMsg("请输入正确的手机号!");
            return result;
        }

        FUser regUser = userMapper.selectByPhone(phone);
        if (regUser == null) {
            result.setSucc(false);
            result.setMsg("未找到该用户!");
            return result;
        }

        if (!StringUtils.equals(regUser.getPwd(), DigestUtils.md5Hex(pwd).toUpperCase())) {
            result.setSucc(false);
            result.setMsg("密码不正确!");
            return result;
        }

        result.setSucc(true);
        regUser.setPwd("");
        result.setData(regUser);
        return result;
    }
}
